package main.service.mail.db;

import main.service.mail.bean.LastTimeBean;
import main.service.mail.util.WUtil;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Date;

public class JDBCLastTime {
    public static void create() {
        Db.execute("create table LastTime (id INTEGER PRIMARY KEY AUTOINCREMENT,"
                + "lastTime varchar(28),"
                + "account varchar(28))");
    }

    public static void drop() {
        try {
            Statement state = Db.getConn().createStatement();
            state.executeUpdate("drop table if exists LastTime");
            state.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    public static LastTimeBean find(String account) {
        LastTimeBean bean = new LastTimeBean();
        try {
            PreparedStatement statement = Db.getConn().prepareStatement("select * from LastTime where account = ?");
            statement.setString(1, account);
            ResultSet resultSet = statement.executeQuery();
            if (resultSet.next()) {
                bean = mapToRow(resultSet);
            }
            statement.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bean;
    }

    public static void insert(String account, Date date) {
        String dateS = WUtil.getDate(date);
        StringBuilder sql = new StringBuilder();
        sql.append("('");
        sql.append(account);
        sql.append("',' ");
        sql.append(dateS);
        sql.append("')");

        Db.execute("insert into LastTime(account, lastTime) values " + sql.toString());
    }

    public static LastTimeBean mapToRow(ResultSet resultSet) throws Exception {
        LastTimeBean bean = new LastTimeBean();
        bean.setAccount(resultSet.getString("account"));
        bean.setId(resultSet.getInt("id"));
        bean.setLastTime(resultSet.getString("lastTime"));
        return bean;
    }
}
